﻿using System;
using System.Collections.Generic;
using System.Linq;
using GatewayBizProcess.Db;

namespace GatewayBizProcess.Facade
{
    public static class BaseInfoBuffer
    {
        private static DateTime _lastLoadTime = DateTime.Now;
        private static List<ps_pollution_source_info> _pollutionSources;
        private static List<ps_pi_port> _ports;
        private static List<sc_pollutant_factor> _factors;

        public static sc_pollutant_factor GetPollutantFactor(int id)
        {
            HotLoadInfo();
            return _factors.FirstOrDefault(t => t.id_ == id);
        }

        public static ps_pi_port GetInfo(string mn)
        {
            HotLoadInfo();
            var port = _ports.FirstOrDefault(t => t.mn.Equals(mn));
            return port;
        }

        public static ps_pi_port GetInfo(int psId, int portId)
        {
            HotLoadInfo();
            var port = _ports.FirstOrDefault(t => t.id == portId && t.ps_base_id == psId);
            return port;
        }

        private static void HotLoadInfo()
        {
            if (_factors == null | _pollutionSources == null || _ports == null || (DateTime.Now - _lastLoadTime).TotalMinutes > 10)
            {
                using (var ctx = new PlatformZrContext())
                {
                    _pollutionSources = ctx.ps_pollution_source_info.ToList();
                    _ports = ctx.ps_pi_port.ToList();
                    _factors = ctx.sc_pollutant_factor.ToList();
                }
                _lastLoadTime = DateTime.Now;
            }
        }


    }
}
